package com.kingsalert.kingsalert.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.kingsalert.kingsalert.R;
import com.kingsalert.kingsalert.bean.config.AccountChannel_Fr;
import com.kingsalert.kingsalert.bean.config.AppShowCustomize;
import com.kingsalert.kingsalert.bean.userinfo.AccountList_Fr;
import com.kingsalert.kingsalert.bean.userinfo.BankAccount_Fr;
import com.kingsalert.kingsalert.config.CountryConfig;
import com.kingsalert.kingsalert.util.http.HttpUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;


public class BindAccountDialog_Cote2 extends Dialog {

    private final FragmentActivity activity;

    private final String page;

    private ImageView channelLogoSelectIv;
    private TextView channelSelectTv;
    private LinearLayout channelListLayout;

    private AccountChannel_Fr selectChannel;

    private final Runnable addActRespRunnable;

    public BindAccountDialog_Cote2(@NonNull FragmentActivity activity,String page,Runnable addActRespRunnable) {
        super(activity);
        this.page = page;
        this.addActRespRunnable = addActRespRunnable;
        this.activity = activity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_bindaccount_cote2);

        getWindow().setBackgroundDrawableResource(R.color.transparent);
        setCanceledOnTouchOutside(false);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        initView();
    }

    @SuppressLint("SetTextI18n")
    private void initView(){

        findViewById(R.id.dbc2_ib_back).setOnClickListener(v -> {
            HttpUtil.getInstance().saveBuriedPoint(page,"OTHER2_CLOSE_CLICK","");
            dismiss();
        });
        findViewById(R.id.dbc2_view_close).setOnClickListener(v -> {
            HttpUtil.getInstance().saveBuriedPoint(page,"OTHER2_NONE_CLICK","");
            dismiss();
        });
        findViewById(R.id.dbc2_ib_customerservice).setOnClickListener(v -> new CustomerServiceDialog(getContext()).show());

        //显示已绑卡
        if (AccountList_Fr.getInstance().getBankAccountList().size()>0){

            BankAccount_Fr account = AccountList_Fr.getInstance().getBankAccountList().get(0);

            ImageView logoIv = findViewById(R.id.dbc2_iv_account_logo);
            TextView accountChannelTv = findViewById(R.id.dbc2_tv_account_channel);
            TextView accountMobileTv = findViewById(R.id.dbc2_tv_account_mobile);

            accountMobileTv.setText(account.getWalletMobile());
            accountChannelTv.setText(account.getWalletDesc());

            //获取图标
            if (account.getBitmap()==null){
                new Thread(() -> {
                    try {
                        if (TextUtils.isEmpty(account.getWalletLogo())) return;
                        URL url = new URL(account.getWalletLogo());
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setConnectTimeout(5000);
                        connection.setRequestMethod("GET");
                        if (connection.getResponseCode()==200){
                            InputStream inputStream = connection.getInputStream();
                            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                            account.setBitmap(bitmap);
                            new Handler(Looper.getMainLooper()).post(() -> logoIv.setImageBitmap(bitmap));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }else logoIv.setImageBitmap(account.getBitmap());

        }

        //渠道选择
        channelLogoSelectIv = findViewById(R.id.dbc2_iv_accountchannel_select);
        channelSelectTv = findViewById(R.id.dbc2_tv_accountchannel_select);
        channelListLayout = findViewById(R.id.dbc2_layout_channel_list);

        findViewById(R.id.dbc2_view_channelselect_click).setOnClickListener(v -> {
            if (channelListLayout.getVisibility() == View.VISIBLE){
                HttpUtil.getInstance().saveBuriedPoint(page,"OTHER2_TYPE_CLICK","");
                channelListLayout.setVisibility(View.GONE);
            }else {
                HttpUtil.getInstance().saveBuriedPoint(page,"OTHER2_TYPE_CLICK","");
                channelListLayout.setVisibility(View.VISIBLE);
            }
        });

        ArrayList<AccountChannel_Fr> channels = AppShowCustomize.getInstance().getAccountChannels();
        for (AccountChannel_Fr channel:channels){
            addChannel(channel);
        }

        //绑卡输入
        TextView areacode1Tv = findViewById(R.id.dbc2_tv_areacode1);
        TextView areacode2Tv = findViewById(R.id.dbc2_tv_areacode2);
        EditText mobile1Et = findViewById(R.id.dbc2_et_mobile1);
        EditText mobile2Et = findViewById(R.id.dbc2_et_mobile2);

        areacode1Tv.setText(CountryConfig.getInstance().getAreaCode());
        areacode2Tv.setText(CountryConfig.getInstance().getAreaCode());

        mobile1Et.setOnFocusChangeListener((v, hasFocus) ->
            HttpUtil.getInstance().saveBuriedPoint(page,"OTHER2_PHONE_INPUT",hasFocus ? "":mobile1Et.getText().toString().trim())
        );

        mobile2Et.setOnFocusChangeListener((v, hasFocus) ->
            HttpUtil.getInstance().saveBuriedPoint(page,"OTHER2_PHONE_CONFIRM_INPUT",hasFocus ? "":mobile2Et.getText().toString().trim())
        );

        //绑卡提交
        findViewById(R.id.dbc2_btn_add).setOnClickListener(v -> {

            HttpUtil.getInstance().saveBuriedPoint(page,"OTHER2_SAVE_CLICK","");

            String mobile1 = mobile1Et.getText().toString().trim();
            String mobile2 = mobile2Et.getText().toString().trim();

            if (TextUtils.isEmpty(mobile1)) mobile1 = "";
            if (TextUtils.isEmpty(mobile2)) mobile2 = "";

            String channel = selectChannel==null ? "":selectChannel.getValue();

            HttpUtil.getInstance().addAccount_Fr(activity,mobile1,mobile2,channel,() -> {
                if (addActRespRunnable != null) addActRespRunnable.run();
            });

            dismiss();

        });

    }

    private void addChannel(AccountChannel_Fr channel){

        View channelView = LayoutInflater.from(getContext()).inflate(R.layout.item_account_channel_fr,null);

        ImageView logoIv = channelView.findViewById(R.id.iacf_iv_logo);
        TextView channelTv = channelView.findViewById(R.id.iacf_tv_channel);

        channelTv.setText(channel.getDesc());

        channelView.findViewById(R.id.iacf_view_click).setOnClickListener(v -> {

            HttpUtil.getInstance().saveBuriedPoint(page,"OTHER2_TYPE_CLICK",channel.getDesc());

            selectChannel = channel;

            channelSelectTv.setText(channel.getDesc());

            channelLogoSelectIv.setVisibility(View.VISIBLE);

            //获取图标
            if (channel.getBitmap()==null){
                new Thread(() -> {
                    try {
                        if (TextUtils.isEmpty(channel.getLogo())) return;
                        URL url = new URL(channel.getLogo());
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setConnectTimeout(5000);
                        connection.setRequestMethod("GET");
                        if (connection.getResponseCode()==200){
                            InputStream inputStream = connection.getInputStream();
                            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                            channel.setBitmap(bitmap);
                            new Handler(Looper.getMainLooper()).post(() -> channelLogoSelectIv.setImageBitmap(bitmap));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }else channelLogoSelectIv.setImageBitmap(channel.getBitmap());

            channelListLayout.setVisibility(View.GONE);

        });

        channelListLayout.addView(channelView);

        //获取图标
        if (channel.getBitmap()==null){
            new Thread(() -> {
                try {
                    if (TextUtils.isEmpty(channel.getLogo())) return;
                    URL url = new URL(channel.getLogo());
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        channel.setBitmap(bitmap);
                        new Handler(Looper.getMainLooper()).post(() -> logoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else logoIv.setImageBitmap(channel.getBitmap());

    }

}









